<template>
  <div>
    <!-- 面包屑 -->
    <div class="mb-6 text-sm text-gray-500 flex items-center">
      <router-link to="/dashboard" class="hover:text-gray-700">控制台</router-link>
      <i class="fas fa-chevron-right mx-2"></i>
      <span class="text-gray-900 font-medium">消缺管理</span>
    </div>

    <!-- 标题与操作 -->
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="text-2xl font-bold text-gray-900">消缺管理</h1>
        <p class="text-gray-600 mt-1">管理缺陷消缺任务、执行进度和回执处理</p>
      </div>
      <div class="flex space-x-3">
        <button @click="handleAddRemedy" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2">
          <i class="fas fa-plus"></i>
          <span>新建消缺任务</span>
        </button>
        <button @click="handleExport" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors flex items-center space-x-2">
          <i class="fas fa-file-export"></i>
          <span>导出数据</span>
        </button>
        <button v-if="selectedTasks.length > 0" @click="handleBatchDelete" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition-colors flex items-center space-x-2">
          <i class="fas fa-trash"></i>
          <span>批量删除 ({{ selectedTasks.length }})</span>
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">待处理</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.pending }}</p>
          </div>
          <div class="bg-yellow-100 p-3 rounded-lg">
            <i class="fas fa-clock text-yellow-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">进行中</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.in_progress }}</p>
          </div>
          <div class="bg-blue-100 p-3 rounded-lg">
            <i class="fas fa-tools text-blue-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">已完成</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.completed }}</p>
          </div>
          <div class="bg-green-100 p-3 rounded-lg">
            <i class="fas fa-check-circle text-green-600 text-xl"></i>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">超时</p>
            <p class="text-3xl font-bold text-gray-900">{{ statistics.timeout }}</p>
          </div>
          <div class="bg-red-100 p-3 rounded-lg">
            <i class="fas fa-exclamation-triangle text-red-600 text-xl"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
      <div class="flex flex-wrap items-center gap-4">
        <div class="flex items-center space-x-2">
          <label class="text-sm font-medium text-gray-700">状态：</label>
          <select v-model="searchForm.status" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            <option v-for="option in statusOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
          </select>
        </div>
        <div class="flex items-center space-x-2">
          <label class="text-sm font-medium text-gray-700">等级：</label>
          <select v-model="searchForm.level" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            <option v-for="option in levelOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
          </select>
        </div>
        <div class="flex items-center space-x-2">
          <label class="text-sm font-medium text-gray-700">负责人：</label>
          <select v-model="searchForm.assignee_id" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            <option v-for="option in assigneeOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
          </select>
        </div>
        <div class="flex items-center space-x-2">
          <label class="text-sm font-medium text-gray-700">时间范围：</label>
          <input v-model="searchForm.start_date" type="date" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
          <span class="text-gray-500">至</span>
          <input v-model="searchForm.end_date" type="date" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
        </div>
        <button @click="handleSearch" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm">
          <i class="fas fa-search mr-1"></i>搜索
        </button>
        <button @click="handleReset" class="bg-gray-100 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-200 transition-colors text-sm">
          <i class="fas fa-redo mr-1"></i>重置
        </button>
        <button @click="handleRefresh" class="bg-gray-100 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-200 transition-colors text-sm">
          <i class="fas fa-sync-alt mr-1"></i>刷新
        </button>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <div class="p-6 border-b border-gray-200">
        <h3 class="text-lg font-semibold text-gray-900">消缺任务列表</h3>
      </div>
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <input 
                  type="checkbox" 
                  :checked="selectAll" 
                  @change="handleSelectAll($event.target.checked)"
                  class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务编号</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">缺陷信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">等级</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">负责人</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">进度</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">截止时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="task in filteredTasks" :key="task.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <input 
                  type="checkbox" 
                  :checked="selectedTasks.includes(task.id)"
                  @change="handleSelect(task.id, $event.target.checked)"
                  class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ task.task_no }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                <div>
                  <div class="font-medium">{{ task.defect_title }}</div>
                  <div class="text-gray-500 text-xs">{{ task.line_name }}</div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getLevelClass(task.level)" class="px-2 py-1 text-xs font-semibold rounded-full">
                  {{ task.level_text }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ task.assignee_name }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(task.status)" class="px-2 py-1 text-xs font-semibold rounded-full">
                  {{ task.status_text }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="w-16 bg-gray-200 rounded-full h-2 mr-2">
                    <div 
                      class="bg-blue-600 h-2 rounded-full" 
                      :style="{ width: task.progress + '%' }"
                    ></div>
                  </div>
                  <span class="text-xs text-gray-600">{{ task.progress }}%</span>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ task.create_time }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ task.deadline }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex space-x-2">
                  <button @click="handleView(task)" class="text-blue-600 hover:text-blue-900">查看</button>
                  <button @click="handleEdit(task)" class="text-green-600 hover:text-green-900">编辑</button>
                  <button v-if="task.status === 'pending'" @click="handleAssign(task)" class="text-purple-600 hover:text-purple-900">分配</button>
                  <button @click="handleDelete(task)" class="text-red-600 hover:text-red-900">删除</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="flex justify-center items-center py-8">
          <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <span class="ml-2 text-gray-600">加载中...</span>
        </div>
        
        <!-- 空状态 -->
        <div v-else-if="filteredTasks.length === 0" class="flex flex-col items-center justify-center py-12">
          <i class="fas fa-inbox text-gray-400 text-4xl mb-4"></i>
          <p class="text-gray-500">暂无消缺任务数据</p>
        </div>
      </div>
      <!-- 分页 -->
      <div class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
        <div class="text-sm text-gray-700">
          显示第 {{ (pagination.pageNum - 1) * pagination.pageSize + 1 }}-{{ Math.min(pagination.pageNum * pagination.pageSize, pagination.total) }} 条，共 {{ pagination.total }} 条记录
        </div>
        <div class="flex items-center space-x-2">
          <button 
            @click="handlePageChange(pagination.pageNum - 1)"
            :disabled="pagination.pageNum <= 1"
            class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            上一页
          </button>
          
          <button 
            v-for="page in Math.min(5, Math.ceil(pagination.total / pagination.pageSize))" 
            :key="page"
            @click="handlePageChange(page)"
            :class="[
              'px-3 py-1 text-sm rounded',
              page === pagination.pageNum 
                ? 'bg-blue-600 text-white' 
                : 'border border-gray-300 hover:bg-gray-50'
            ]"
          >
            {{ page }}
          </button>
          
          <button 
            @click="handlePageChange(pagination.pageNum + 1)"
            :disabled="pagination.pageNum >= Math.ceil(pagination.total / pagination.pageSize)"
            class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 消缺任务详情/编辑弹窗 -->
    <div v-if="dialogVisible" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="flex items-center justify-between p-6 border-b border-gray-200">
          <h3 class="text-lg font-semibold text-gray-900">{{ dialogTitle }}</h3>
          <button @click="dialogVisible = false" class="text-gray-400 hover:text-gray-600">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="p-6">
          <form @submit.prevent="handleSave">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">选择缺陷 * (共{{ defectOptionsCount }}条)</label>
                <select 
                  v-model="formData.defect_id" 
                  :disabled="dialogMode === 'view'"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  @change="onDefectChange"
                >
                  <option value="">请选择缺陷</option>
                  <option v-for="defect in defectOptions" :key="defect.id" :value="defect.id">
                    {{ defect.code }} - {{ defect.description }}
                  </option>
                </select>
                <div v-if="defectOptions.length === 0" class="text-red-500 text-sm mt-1">
                  正在加载缺陷选项...
                </div>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">缺陷标题</label>
                <input 
                  v-model="formData.defect_title" 
                  type="text" 
                  readonly
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-50"
                  placeholder="选择缺陷后自动填充"
                />
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">线路名称 *</label>
                <input 
                  v-model="formData.line_name" 
                  type="text" 
                  :disabled="dialogMode === 'view'"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入线路名称"
                />
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">缺陷等级 *</label>
                <select 
                  v-model="formData.level" 
                  :disabled="dialogMode === 'view'"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="low">低危</option>
                  <option value="general">一般</option>
                  <option value="serious">严重</option>
                  <option value="critical">危急</option>
                  <option value="high">高危</option>
                  <option value="emergency">紧急</option>
                </select>
              </div>
              
              <div v-if="dialogMode === 'edit' || dialogMode === 'view'">
                <label class="block text-sm font-medium text-gray-700 mb-2">负责人 *</label>
                <select 
                  v-model="formData.assignee_name" 
                  :disabled="dialogMode === 'view'"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="">请选择负责人</option>
                  <option v-for="option in assigneeOptions.slice(1)" :key="option.value" :value="option.label">{{ option.label }}</option>
                </select>
              </div>
              
              <div v-if="dialogMode === 'edit' || dialogMode === 'view'">
                <label class="block text-sm font-medium text-gray-700 mb-2">任务状态</label>
                <select 
                  v-model="formData.status" 
                  :disabled="dialogMode === 'view'"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="pending">待处理</option>
                  <option value="assigned">已分配</option>
                  <option value="in_progress">进行中</option>
                  <option value="completed">已完成</option>
                  <option value="timeout">超时</option>
                  <option value="cancelled">已取消</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">截止时间 *</label>
                <input 
                  v-model="formData.deadline" 
                  type="datetime-local" 
                  :disabled="dialogMode === 'view'"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              
              <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-2">任务描述</label>
                <textarea 
                  v-model="formData.description" 
                  :disabled="dialogMode === 'view'"
                  rows="3"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入任务描述"
                ></textarea>
              </div>
            </div>
            
            <div v-if="dialogMode !== 'view'" class="flex justify-end space-x-3 mt-6">
              <button 
                type="button" 
                @click="dialogVisible = false"
                class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 border border-gray-300 rounded-lg hover:bg-gray-200 focus:ring-2 focus:ring-gray-500"
              >
                取消
              </button>
              <button 
                type="submit"
                class="px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500"
              >
                保存
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 任务分配弹窗 -->
    <div v-if="assignDialogVisible" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="flex items-center justify-between p-6 border-b border-gray-200">
          <h3 class="text-lg font-semibold text-gray-900">分配任务</h3>
          <button @click="assignDialogVisible = false" class="text-gray-400 hover:text-gray-600">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="p-6">
          <form @submit.prevent="handleAssignSave">
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">负责人 *</label>
                <select 
                  v-model="assignForm.assignee_name" 
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="">请选择负责人</option>
                  <option v-for="option in assigneeOptions.slice(1)" :key="option.value" :value="option.label">{{ option.label }}</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">截止时间 *</label>
                <input 
                  v-model="assignForm.deadline" 
                  type="datetime-local" 
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">分配说明</label>
                <textarea 
                  v-model="assignForm.description" 
                  rows="3"
                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入分配说明"
                ></textarea>
              </div>
            </div>
            
            <div class="flex justify-end space-x-3 mt-6">
              <button 
                type="button" 
                @click="assignDialogVisible = false"
                class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 border border-gray-300 rounded-lg hover:bg-gray-200 focus:ring-2 focus:ring-gray-500"
              >
                取消
              </button>
              <button 
                type="submit"
                class="px-4 py-2 text-sm font-medium text-white bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:ring-2 focus:ring-purple-500"
              >
                分配
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { remedyAPI, defectAPI, statisticsAPI } from '@/api/modules'

// 响应式数据
const remedyTasks = ref([])
const loading = ref(false)
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  status: '',
  level: '',
  assignee_id: '',
  start_date: '',
  end_date: ''
})

// 统计信息
const statistics = ref({
  pending: 0,
  in_progress: 0,
  completed: 0,
  timeout: 0
})

// 选中的任务
const selectedTasks = ref([])
const selectAll = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMode = ref('') // add, edit, view
const formData = reactive({
  id: null,
  defect_id: '',
  defect_title: '',
  line_name: '',
  level: 'general',
  assignee_id: '',
  assignee_name: '',
  status: 'pending',
  description: '',
  deadline: '',
  priority: 'medium'
})

// 分配弹窗
const assignDialogVisible = ref(false)
const assignForm = reactive({
  assignee_id: '',
  assignee_name: '',
  deadline: '',
  description: '',
  taskId: null
})

// 选项数据
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待处理', value: 'pending' },
  { label: '已分配', value: 'assigned' },
  { label: '进行中', value: 'in_progress' },
  { label: '已完成', value: 'completed' },
  { label: '超时', value: 'timeout' },
  { label: '已取消', value: 'cancelled' }
]

const levelOptions = [
  { label: '全部', value: '' },
  { label: '低危', value: 'low' },
  { label: '一般', value: 'general' },
  { label: '严重', value: 'serious' },
  { label: '危急', value: 'critical' },
  { label: '高危', value: 'high' },
  { label: '紧急', value: 'emergency' }
]

const assigneeOptions = ref([
  { label: '全部', value: '' }
])

// 缺陷选项
const defectOptions = ref([])

// 调试用计算属性
const defectOptionsCount = computed(() => {
  console.log('缺陷选项数量:', defectOptions.value.length)
  return defectOptions.value.length
})

const priorityOptions = [
  { label: '低', value: 'low' },
  { label: '中', value: 'medium' },
  { label: '高', value: 'high' },
  { label: '紧急', value: 'urgent' }
]

// 移除硬编码的模拟数据，确保数据都来自后端API

// 计算属性
const filteredTasks = computed(() => {
  let tasks = remedyTasks.value
  
  if (searchForm.status) {
    tasks = tasks.filter(task => task.status === searchForm.status)
  }
  
  if (searchForm.level) {
    tasks = tasks.filter(task => task.level === searchForm.level)
  }
  
  if (searchForm.assignee_id) {
    tasks = tasks.filter(task => task.assignee_id === parseInt(searchForm.assignee_id))
  }
  
  if (searchForm.start_date && searchForm.end_date) {
    tasks = tasks.filter(task => {
      const createDate = new Date(task.create_time.split(' ')[0])
      const startDate = new Date(searchForm.start_date)
      const endDate = new Date(searchForm.end_date)
      return createDate >= startDate && createDate <= endDate
    })
  }
  
  return tasks
})

const statusText = computed(() => {
  const statusMap = {
    pending: '待处理',
    assigned: '已分配',
    in_progress: '进行中',
    completed: '已完成',
    timeout: '超时',
    cancelled: '已取消'
  }
  return statusMap[formData.status] || '未知'
})

const levelText = computed(() => {
  const levelMap = {
    low: '低危',
    general: '一般',
    serious: '严重',
    critical: '危急',
    high: '高危',
    emergency: '紧急'
  }
  return levelMap[formData.level] || '未知'
})

// 方法
const loadRemedyList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      keyword: searchForm.keyword || undefined,
      status: searchForm.status || undefined,
      level: searchForm.level || undefined,
      assigneeId: searchForm.assignee_id || undefined
    }
    
    const response = await remedyAPI.getRemedies(params)
    
    if (response.code === 0) {
      const data = response.data
      // 映射后端字段到前端期望的字段
      remedyTasks.value = (data.records || []).map(item => {
        // 等级名称到英文值的映射
        const levelMap = {
          '低危': 'low',
          '一般': 'general',
          '严重': 'serious',
          '危急': 'critical',
          '高危': 'high',
          '紧急': 'emergency'
        }
        
        return {
          ...item,
          task_no: item.taskNo,                    // 将taskNo映射到task_no
          defect_title: item.defectTypeName || item.defectCode, // 将defectTypeName映射到defect_title
          line_name: item.lineName || '未知线路',   // 将lineName映射到line_name
          level: levelMap[item.levelName] || 'general', // 将levelName映射到level（英文值）
          level_text: item.levelName,              // 将levelName映射到level_text（中文显示）
          assignee_name: item.assigneeName,       // 将assigneeName映射到assignee_name
          status_text: getStatusText(item.status), // 将status映射到status_text
          create_time: item.createTime,           // 将createTime映射到create_time
          deadline: item.deadline,                // 直接使用deadline
          progress: item.progress || 0            // 直接使用progress
        }
      })
      
      // 更新分页信息
      pagination.value.total = data.total || 0
      pagination.value.pages = data.pages || 0
      
      // 更新统计数据
      updateStatistics()
    } else {
      throw new Error(response.message || '获取消缺任务列表失败')
    }
    
  } catch (error) {
    console.error('加载消缺任务列表失败:', error)
    ElMessage.error('加载消缺任务列表失败')
  } finally {
    loading.value = false
  }
}

const updateStatistics = async () => {
  try {
    const response = await remedyAPI.getRemedyStatistics()
    
    if (response.code === 0) {
      const data = response.data
      statistics.value = {
        pending: data.pending || 0,
        in_progress: data.inProgress || 0,
        completed: data.completed || 0,
        timeout: data.timeout || 0
      }
    } else {
      console.error('获取消缺统计失败:', response.message)
    }
  } catch (error) {
    console.error('获取消缺统计失败:', error)
  }
}

const handleSearch = () => {
  pagination.value.pageNum = 1
  loadRemedyList()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.value.pageNum = 1
  loadRemedyList()
}

const handleRefresh = () => {
  loadRemedyList()
}

const handlePageChange = (page) => {
  pagination.value.pageNum = page
  loadRemedyList()
}

const handleSelectAll = (checked) => {
  selectAll.value = checked
  if (checked) {
    selectedTasks.value = filteredTasks.value.map(task => task.id)
  } else {
    selectedTasks.value = []
  }
}

const handleSelect = (taskId, checked) => {
  if (checked) {
    if (!selectedTasks.value.includes(taskId)) {
      selectedTasks.value.push(taskId)
    }
  } else {
    const index = selectedTasks.value.indexOf(taskId)
    if (index > -1) {
      selectedTasks.value.splice(index, 1)
    }
  }
  
  selectAll.value = selectedTasks.value.length === filteredTasks.value.length
}

const handleAddRemedy = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '新建消缺任务'
  
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    if (key === 'id') {
      formData[key] = null
    } else if (key === 'status') {
      formData[key] = 'pending'
    } else if (key === 'level') {
      formData[key] = 'general'
    } else if (key === 'priority') {
      formData[key] = 'medium'
    } else {
      formData[key] = ''
    }
  })
  
  // 确保缺陷选项已加载
  if (defectOptions.value.length === 0) {
    loadDefectOptions()
  }
  
  dialogVisible.value = true
}

// 缺陷选择变化处理
const onDefectChange = () => {
  const selectedDefect = defectOptions.value.find(defect => defect.id == formData.defect_id)
  if (selectedDefect) {
    // 等级名称到英文值的映射
    const levelMap = {
      '低危': 'low',
      '一般': 'general',
      '严重': 'serious',
      '危急': 'critical',
      '高危': 'high',
      '紧急': 'emergency'
    }
    
    formData.defect_title = selectedDefect.description
    formData.line_name = selectedDefect.lineName || ''
    formData.line_id = selectedDefect.lineId || null
    formData.level = levelMap[selectedDefect.levelName] || 'general'  // 映射为英文值
    formData.level_id = selectedDefect.levelId || null
  }
}

// 加载缺陷选项
const loadDefectOptions = async () => {
  try {
    console.log('开始加载缺陷选项...')
    const response = await defectAPI.getDefects({ pageNum: 1, pageSize: 100 })
    console.log('缺陷API响应:', response)
    if (response.code === 0) {
      defectOptions.value = response.data.records || []
      console.log('缺陷选项加载成功:', defectOptions.value.length, '条记录')
    } else {
      console.error('缺陷API返回错误:', response.message)
    }
  } catch (error) {
    console.error('加载缺陷选项失败:', error)
  }
}

const handleEdit = (task) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑消缺任务'
  
  // 等级ID到字符串的映射
  const levelMap = {
    4: 'low',      // 低危
    1: 'general',  // 一般
    2: 'serious',  // 严重
    3: 'critical', // 危急
    5: 'high',     // 高危
    6: 'emergency' // 紧急
  }
  
  console.log('编辑任务数据:', task)
  console.log('当前用户选项:', assigneeOptions.value)
  
  // 填充表单数据，使用已映射的字段
  Object.assign(formData, {
    ...task,
    defect_id: task.defectId,                     // 设置缺陷ID
    defect_title: task.defect_title,              // 使用已映射的defect_title
    line_name: task.line_name,                    // 使用已映射的line_name
    line_id: task.lineId,                         // 设置线路ID
    level: levelMap[task.levelId] || 'general',   // 将levelId映射到level字符串
    level_id: task.levelId,                       // 设置等级ID
    assignee_id: task.assigneeId,                 // 设置负责人ID
    assignee_name: task.assignee_name,            // 使用已映射的assignee_name
    status: task.status,                           // 直接使用status
    description: task.description,                // 直接使用description
    deadline: task.deadline                       // 直接使用deadline
  })
  
  console.log('填充后的表单数据:', formData)
  console.log('负责人名称匹配检查:', assigneeOptions.value.find(option => option.label === formData.assignee_name))
  
  dialogVisible.value = true
}

const handleView = (task) => {
  dialogMode.value = 'view'
  dialogTitle.value = '查看消缺任务'
  
  // 等级ID到字符串的映射
  const levelMap = {
    4: 'low',      // 低危
    1: 'general',  // 一般
    2: 'serious',  // 严重
    3: 'critical', // 危急
    5: 'high',     // 高危
    6: 'emergency' // 紧急
  }
  
  // 填充表单数据，使用已映射的字段
  Object.assign(formData, {
    ...task,
    defect_id: task.defectId,                     // 设置缺陷ID
    defect_title: task.defect_title,              // 使用已映射的defect_title
    line_name: task.line_name,                    // 使用已映射的line_name
    line_id: task.lineId,                         // 设置线路ID
    level: levelMap[task.levelId] || 'general',   // 将levelId映射到level字符串
    level_id: task.levelId,                       // 设置等级ID
    assignee_id: task.assigneeId,                 // 设置负责人ID
    assignee_name: task.assignee_name,            // 使用已映射的assignee_name
    status: task.status,                           // 直接使用status
    description: task.description,                // 直接使用description
    deadline: task.deadline                       // 直接使用deadline
  })
  
  dialogVisible.value = true
}

const handleDelete = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除消缺任务 "${task.task_no}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API删除
    const response = await remedyAPI.deleteRemedy(task.id)
    
    if (response.code === 0) {
      // 从列表中移除
      const index = remedyTasks.value.findIndex(item => item.id === task.id)
      if (index > -1) {
        remedyTasks.value.splice(index, 1)
        pagination.value.total--
      }
      
      updateStatistics()
      ElMessage.success('删除成功')
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchDelete = async () => {
  if (selectedTasks.value.length === 0) {
    ElMessage.warning('请选择要删除的任务')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedTasks.value.length} 个消缺任务吗？`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 显示删除进度
    const loadingMessage = ElMessage({
      message: '正在删除任务...',
      type: 'info',
      duration: 0,
      showClose: false
    })
    
    try {
      // 循环调用单个删除API
      const deletePromises = selectedTasks.value.map(taskId => 
        remedyAPI.deleteRemedy(taskId)
      )
      
      const responses = await Promise.all(deletePromises)
      
      // 关闭进度提示
      loadingMessage.close()
      
      // 检查所有删除是否成功
      const successCount = responses.filter(response => response.code === 0).length
      const failedCount = responses.length - successCount
      
      if (failedCount === 0) {
        // 从列表中移除选中的任务
        remedyTasks.value = remedyTasks.value.filter(task => !selectedTasks.value.includes(task.id))
        pagination.value.total -= successCount
        
        selectedTasks.value = []
        selectAll.value = false
        
        updateStatistics()
        ElMessage.success(`批量删除 ${successCount} 个任务成功`)
      } else {
        // 部分成功的情况
        const successTaskIds = selectedTasks.value.slice(0, successCount)
        remedyTasks.value = remedyTasks.value.filter(task => !successTaskIds.includes(task.id))
        pagination.value.total -= successCount
        
        ElMessage.warning(`批量删除完成：成功删除 ${successCount} 个任务，${failedCount} 个任务删除失败`)
        
        // 清空选择，但保留失败的任务在列表中
        selectedTasks.value = []
        selectAll.value = false
        updateStatistics()
      }
    } catch (deleteError) {
      // 关闭进度提示
      loadingMessage.close()
      throw deleteError
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleAssign = (task) => {
  assignDialogVisible.value = true
  
  // 填充分配表单，使用已映射的字段
  Object.assign(assignForm, {
    assignee_id: task.assigneeId || '',           // 将assigneeId映射到assignee_id
    assignee_name: task.assignee_name || '',      // 使用已映射的assignee_name
    deadline: task.deadline || '',               // 直接使用deadline
    description: task.description || '',         // 直接使用description
    taskId: task.id                              // 存储当前任务ID
  })
}


const handleSave = async () => {
  try {
    // 表单验证
    if (!formData.defect_id) {
      ElMessage.error('请选择缺陷')
      return
    }
    
    if (!formData.line_name) {
      ElMessage.error('请输入线路名称')
      return
    }
    
    // 新增时不验证负责人，编辑时才验证
    if ((dialogMode.value === 'edit' || dialogMode.value === 'view') && !formData.assignee_name) {
      ElMessage.error('请选择负责人')
      return
    }
    
    // 根据选择的负责人名称找到对应的ID
    let assigneeId = null
    if (formData.assignee_name) {
      console.log('查找负责人:', formData.assignee_name)
      console.log('可用选项:', assigneeOptions.value)
      const selectedAssignee = assigneeOptions.value.find(option => option.label === formData.assignee_name)
      console.log('找到的负责人:', selectedAssignee)
      if (selectedAssignee) {
        assigneeId = parseInt(selectedAssignee.value)
        console.log('负责人ID:', assigneeId)
      } else {
        console.error('未找到匹配的负责人选项')
      }
    }
    
    if (!formData.deadline) {
      ElMessage.error('请选择截止时间')
      return
    }
    
    // 构建请求数据，将前端字段映射到后端字段
    const requestData = {
      defectId: parseInt(formData.defect_id),
      lineId: parseInt(formData.line_id) || null,
      levelId: parseInt(formData.level_id) || null,
      assigneeId: assigneeId,
      status: formData.status || 'pending',
      description: formData.description || '',
      deadline: formData.deadline ? new Date(formData.deadline).toISOString() : null,
      startTime: formData.start_time ? new Date(formData.start_time).toISOString() : null,
      completeTime: formData.complete_time ? new Date(formData.complete_time).toISOString() : null,
      progress: formData.progress || 0,
      imagesJson: formData.images_json || null,
      materials: formData.materials || []
    }
    
    let response
    if (dialogMode.value === 'add') {
      response = await remedyAPI.createRemedy(requestData)
    } else {
      response = await remedyAPI.updateRemedy(formData.id, requestData)
    }
    
    if (response.code === 0) {
      ElMessage.success(dialogMode.value === 'add' ? '新建消缺任务成功' : '更新消缺任务成功')
      dialogVisible.value = false
      loadRemedyList()
      updateStatistics()
    } else {
      throw new Error(response.message || '保存失败')
    }
    
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

const handleAssignSave = async () => {
  try {
    // 表单验证
    if (!assignForm.assignee_name) {
      ElMessage.error('请选择负责人')
      return
    }
    
    if (!assignForm.deadline) {
      ElMessage.error('请选择截止时间')
      return
    }
    
    // 根据选择的负责人名称找到对应的ID
    const selectedAssignee = assigneeOptions.value.find(option => option.label === assignForm.assignee_name)
    if (!selectedAssignee) {
      ElMessage.error('请选择有效的负责人')
      return
    }
    
    // 构建分配请求数据
    const assignData = {
      assigneeId: parseInt(selectedAssignee.value),
      deadline: assignForm.deadline ? new Date(assignForm.deadline).toISOString() : null,
      description: assignForm.description || ''
    }
    
    let response
    if (assignForm.taskId) {
      // 单个任务分配
      response = await remedyAPI.assignRemedy(assignForm.taskId, assignData)
      
      if (response.code === 0) {
        ElMessage.success('任务分配成功')
        loadRemedyList()
        updateStatistics()
        assignDialogVisible.value = false
      } else {
        throw new Error(response.message || '分配失败')
      }
    }
  } catch (error) {
    console.error('分配失败:', error)
    ElMessage.error('分配失败')
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

const getLevelClass = (level) => {
  const classes = {
    general: 'bg-green-100 text-green-800',
    serious: 'bg-yellow-100 text-yellow-800',
    urgent: 'bg-red-100 text-red-800'
  }
  return classes[level] || 'bg-gray-100 text-gray-800'
}

const getStatusClass = (status) => {
  const classes = {
    pending: 'bg-yellow-100 text-yellow-800',
    assigned: 'bg-blue-100 text-blue-800',
    in_progress: 'bg-blue-100 text-blue-800',
    completed: 'bg-green-100 text-green-800',
    timeout: 'bg-red-100 text-red-800',
    cancelled: 'bg-gray-100 text-gray-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

const getLevelText = (level) => {
  const levelMap = {
    general: '一般',
    serious: '严重',
    urgent: '紧急'
  }
  return levelMap[level] || '未知'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    assigned: '已分配',
    in_progress: '进行中',
    completed: '已完成',
    timeout: '超时',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

/**
 * 加载用户选项
 */
const loadUserOptions = async () => {
  try {
    console.log('开始加载用户选项...')
    const response = await statisticsAPI.getUsers()
    console.log('用户API响应:', response)
    
    if (response.code === 0) {
      const users = response.data || []
      console.log('获取到用户数据:', users)
      
      // 构建用户选项，保留"全部"选项
      const options = [
        { label: '全部', value: '' },
        ...users.map(user => ({
          label: user.name || user.username || `用户${user.id}`,
          value: user.id
        }))
      ]
      
      assigneeOptions.value = options
      console.log('用户选项加载成功:', assigneeOptions.value.length, '个选项')
    } else {
      console.error('用户API返回错误:', response.message)
    }
  } catch (error) {
    console.error('加载用户选项失败:', error)
  }
}

onMounted(() => {
  loadRemedyList()
  loadDefectOptions()
  loadUserOptions()
})
</script>

<style scoped>
/* 表格样式优化 */
table {
  border-collapse: separate;
  border-spacing: 0;
}

th {
  position: sticky;
  top: 0;
  z-index: 10;
}
</style>
